//
//  MainViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/6/27.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "MainViewController.h"
#import "MainLeftView.h"
#import "MainView.h"
#import "PlanModel.h"
#import "MainViewCell.h"
#import "ChildListViewController.h"
#import "ClassManageViewController.h"
#import "SaleSituationViewController.h"
#import "TestPlanViewController.h"
#import "ContinuePlanViewController.h"
#import "LoginNewViewController.h"
@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) MainLeftView * mainLeftView;
@property (nonatomic,strong) MainView * mainView;
@property (nonatomic,strong) PlanModel * planModel;
@property (nonatomic,strong) NSMutableArray * planArray;
@property (nonatomic,strong) NSMutableArray * joinNumberArray;
@property (nonatomic,assign) NSInteger manyChildUsing;
@property (nonatomic,strong) NSMutableDictionary * allDataDictionary;
@property (nonatomic,strong) UILabel * noDataLabel;
@end

@implementation MainViewController
//-(void)viewDidLayoutSubviews
//{
//    _mainView.myScrollView.contentSize = CGSizeMake(0,(240+85*self.planArray.count)*AutoScaleVertical );
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(241, 244, 248);
    self.title = @"主页";
    [self.navigationController.navigationBar setTitleTextAttributes:
  @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
    NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 25,25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"naviLeft"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.mainView.myTableView !=nil) {
        [self.mainView.myTableView removeFromSuperview];
    }
    if (self.noDataLabel !=nil) {
        [self.noDataLabel removeFromSuperview];
    }
    [self getData];
}
//左导航按钮
-(void)leftBarBtnClicked{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pressOff)];
    [_backView addGestureRecognizer:tap];
    
    [window bringSubviewToFront:_mainLeftView];
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(0, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
}
//收起左边抽屉
-(void)pressOff{
    NSLog(@"收起");
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
}
//获取数据
-(void)getData{
    self.planArray =[[NSMutableArray alloc]init];// 存放计划模型
    NSMutableArray * projectIDarray = [[NSMutableArray alloc]initWithCapacity:0];//存放当前拥有计划的ID ，用以查询有多少人在这个计划中
    self.joinNumberArray = [[NSMutableArray alloc]initWithCapacity:0];//存放每个计划有多少人参加
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //取出Programs   PLAN 模型加入数组
    NSMutableArray * userPlanArr = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"Programs"]];
//    //根据创建时间倒序排列
//    for (int  i =0; i<[userPlanArr count]-1; i++) {
//        
//        for (int j = i+1; j<[userPlanArr count]; j++) {
//            
//            NSMutableDictionary * dic = userPlanArr[i];
//            NSString * birthStr = [[dic objectForKey:@"CreateTime"] substringWithRange:NSMakeRange(0, 10)];
//            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//            NSDate *birthDate = [dateFormatter dateFromString:birthStr];
//            NSString * realAge = [self dateToDetailOld:birthDate];
//            
//            
//            NSMutableDictionary * dict = userPlanArr[j];
//            NSString * birthStr1 = [[dict objectForKey:@"CreateTime"] substringWithRange:NSMakeRange(0, 10)];
//            NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
//            [dateFormatter1 setDateFormat:@"yyyy-MM-dd"];
//            NSDate *birthDate1 = [dateFormatter1 dateFromString:birthStr1];
//            NSString * realAge1 = [self dateToDetailOld:birthDate1];
//            
//            if ([realAge intValue]>[realAge1 intValue]) {
//                
//                //交换
//                
//                [userPlanArr exchangeObjectAtIndex:i withObjectAtIndex:j];
//                
//            }
//            
//        }
//        
//    }
    
    for (NSDictionary * dic in userPlanArr) {
        if (![[dic objectForKey:@"Type"]isEqual:@0] && ![[dic objectForKey:@"Status"]boolValue]) {
            PlanModel * model = [PlanModel modelWithDictionary:dic];
            [self.planArray addObject:model];
            [projectIDarray addObject:model.Id];
        }
        
    }
    
    
    //循环遍历看有多少人参加了现有的计划
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
    NSMutableArray * childArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"ChildList"]];
    for (NSNumber * num in projectIDarray) {
        NSInteger joinProNumber = 0;
//        for (NSMutableDictionary * childDic in childArray) {
        
        
        for (NSDictionary * dict in testArray) {
            NSDictionary * masterdic = [dict objectForKey:@"master"];
            
//            if ([[childDic objectForKey:@"Id"]isEqual:[masterdic objectForKey:@"ChildId"]]) {
            
            if ([[masterdic objectForKey:@"ProgramId"]isEqual:num]) {
                joinProNumber += 1;
            }
            }
//        }
        
//    }
        NSNumber * joinNum = [NSNumber numberWithInt:joinProNumber];
        [self.joinNumberArray addObject:joinNum];
    }
//    [user synchronize];
//    [self setUI];/
    [self setUI];
//    [self.mainView.myTableView reloadData];
    //主页面scrollview偏移距离
    _mainView.myScrollView.contentSize = CGSizeMake(0,(324+85*self.planArray.count)*AutoScaleVertical );//整个SCVIEW 的竖向偏移距离
}

//创建UI
-(void)setUI{
    //创建侧边栏
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _mainLeftView = [[MainLeftView alloc]initWithFrame:CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT)];
    _mainLeftView.iconLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"companyName"];
    [window addSubview:_mainLeftView];
    [_mainLeftView.offBTN addTarget:self action:@selector(pressOff) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.reloadBtn addTarget:self action:@selector(pressReload) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.problemLoadBtn addTarget:self action:@selector(pressProblem) forControlEvents:UIControlEventTouchUpInside];
    [_mainLeftView.quitBtn addTarget:self action:@selector(sureToQuit) forControlEvents:UIControlEventTouchUpInside];
    //创建MAINVIEW
    self.mainView = [[MainView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_mainView];
    
    if (self.planArray.count ==0) {
        _noDataLabel = [[UILabel alloc]init];
        _noDataLabel.text = @"还没有测试计划";
        _noDataLabel.textColor = [UIColor blackColor];
        _noDataLabel.font = [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal];
        [self.view addSubview:_noDataLabel];
        [_noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.centerY.mas_equalTo(self.view.mas_centerY);
            
        }];
    }else{
    //有数据时创建列表
    _mainView.myTableView = [[UITableView alloc]init];
    _mainView.myTableView.backgroundColor =UIColorFromRGB(241, 244, 248);
    _mainView.myTableView.delegate =self;
    _mainView.myTableView.dataSource =self;
    _mainView.myTableView.showsVerticalScrollIndicator =NO;
    //无分割线
    _mainView.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //多余的CELL 隐藏
    _mainView.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [_mainView.myTableView registerClass:[MainViewCell class] forCellReuseIdentifier:@"MainViewCell"];
    [_mainView.myScrollView addSubview:_mainView.myTableView];
    [_mainView.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_mainView.testingLabel.mas_bottom).with.offset(25*AutoScaleVertical);
        make.left.mas_equalTo(_mainView.testingLabel.mas_left);
        make.right.mas_equalTo(_mainView.saleSituationBtn.mas_right);
        make.height.mas_equalTo(85*self.planArray.count);
    }];
    }
    //四按钮
    [_mainView.childListBtn addTarget:self action:@selector(pressChildList) forControlEvents:UIControlEventTouchUpInside];
    [_mainView.classManageBtn addTarget:self action:@selector(pressClassManage) forControlEvents:UIControlEventTouchUpInside];
    [_mainView.testPlanBtn addTarget:self action:@selector(pressTestPlan) forControlEvents:UIControlEventTouchUpInside];
    [_mainView.saleSituationBtn addTarget:self action:@selector(pressSaleSituation) forControlEvents:UIControlEventTouchUpInside];
    

}
#pragma mark tableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85*AutoScaleVertical;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.planArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MainViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MainViewCell"];
    //cell.userInteractionEnabled = NO;
    if (cell == nil) {
        cell = [[MainViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: @"MainViewCell"] ;
        //        cell.selectedBackgroundView.backgroundColor = [HexColor colorWithHexString:@"#00bcab"];
        //        cell.textLabel.highlightedTextColor = [HexColor colorWithHexString:@"#fffff"];
    }

    [cell relayoutCellWithModel:self.planArray[indexPath.row] andIndex:indexPath.row andArrCount:self.planArray.count andNumber:self.joinNumberArray[indexPath.row]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ContinuePlanViewController * cvc = [[ContinuePlanViewController alloc]init];
    PlanModel * model = self.planArray[indexPath.row];
    cvc.ownModel = model;
    [self.navigationController pushViewController:cvc animated:YES];
    
}
#pragma mark 侧边栏3按钮方法
////////////////////////////////////1
-(void)pressReload{
    NSLog(@"同步数据");
    [self uploadData];
}
//问题上传
-(void)pressProblem{
    NSLog(@"问题上传");
    [self uploadProblemData];
}

#pragma mark 退出登陆相关

#pragma mark 删除组
-(void)sureToQuit{
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView1.backgroundColor = [UIColor blackColor];
    _backView1.alpha = 0.52;
    [window addSubview:_backView1];
    
    _backWhiteView = [[UIView alloc]init];
    _backWhiteView.backgroundColor = UIColorFromRGB(26, 167, 157);
    _backWhiteView.layer.cornerRadius= 10;
    _backWhiteView.layer.masksToBounds =YES;
    [window addSubview:_backWhiteView];
    [_backWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_backView1.mas_centerX);
        make.top.mas_equalTo(_backView1.mas_top).with.offset(160*AutoScaleVertical);
        make.width.mas_equalTo(600*AutoScaleHorizontal);
        make.height.mas_equalTo(400*AutoScaleVertical);
    }];
    
    self.backLabel = [[UILabel alloc]init];
    self.backLabel.font = [UIFont systemFontOfSize:16*AutoScaleHorizontal];
    self.backLabel.text = @"提示";
    self.backLabel.textColor = [UIColor whiteColor];
    [self.backLabel setTextAlignment:NSTextAlignmentCenter];
    [window addSubview:self.backLabel];
    [self.backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backWhiteView.mas_centerX);
        make.top.mas_equalTo(self.backWhiteView.mas_top).with.offset(20*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    
    
    self.backLineView = [[UIView alloc]init];
    self.backLineView.backgroundColor =UIColorFromRGB(241, 241, 241);
    [window addSubview:self.backLineView];
    [self.backLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backWhiteView.mas_top).with.offset(50*AutoScaleVertical);
        make.left.mas_equalTo(self.backWhiteView.mas_left);
        make.width.mas_equalTo(self.backWhiteView);
        make.height.mas_equalTo(1*AutoScaleVertical);
    }];
    
    self.backLabel1 = [[UILabel alloc]init];
    self.backLabel1.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [self.backLabel1 setTextAlignment:NSTextAlignmentCenter];
    self.backLabel1.text = @"确定退出登录吗？";
    self.backLabel1.textColor = [UIColor whiteColor];
    [window addSubview:self.backLabel1];
    [self.backLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backWhiteView.mas_centerX);
        make.top.mas_equalTo(self.backLineView.mas_top).with.offset(100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    
    
    self.backDeleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backDeleteBtn.layer.cornerRadius =10;
    self.backDeleteBtn.layer.borderWidth =1;
    self.backDeleteBtn.layer.borderColor = [UIColor whiteColor].CGColor;
//    [self.backDeleteBtn setBackgroundImage:[UIImage imageNamed:@"noBtn"] forState:UIControlStateNormal];
    [self.backDeleteBtn setTitle:@"我再想想" forState:UIControlStateNormal];
    [self.backDeleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.backDeleteBtn addTarget:self action:@selector(sureNos) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.backDeleteBtn];
    [self.backDeleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backWhiteView.mas_left).with.offset(150*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.backWhiteView.mas_bottom).with.offset(-100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
    
    self.backConfirmBtn = [[UIButton alloc]init];
        self.backConfirmBtn.layer.cornerRadius =10;
    self.backConfirmBtn.layer.borderWidth =1;
    self.backConfirmBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.backConfirmBtn setTitle:@"我确定了" forState:UIControlStateNormal];
    [self.backConfirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.backConfirmBtn setBackgroundImage:[UIImage imageNamed:@"yesBtn"] forState:UIControlStateNormal];
    [self.backConfirmBtn addTarget:self action:@selector(sureYess) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.backConfirmBtn];
    [self.backConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.backWhiteView.mas_right).with.offset(-150*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.backWhiteView.mas_bottom).with.offset(-100*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(100*AutoScaleHorizontal, 30*AutoScaleVertical));
    }];
}
//取消
-(void)sureNos{
    
    [self.backView1 removeFromSuperview];
    [self.backWhiteView removeFromSuperview];
    [self.backDeleteBtn removeFromSuperview];
    [self.backConfirmBtn removeFromSuperview];
    [self.backLabel removeFromSuperview];
    [self.backLineView removeFromSuperview];
    [self.backLabel1 removeFromSuperview];
}
//确定
-(void)sureYess{
   
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            //移除UserDefaults中存储的用户信息
//            [userDefaults removeObjectForKey:@"UserName"];
            [userDefaults removeObjectForKey:@"PassWord"];
            [userDefaults removeObjectForKey:@"isLogin"];
            [userDefaults synchronize];
            [self.backView1 removeFromSuperview];
            [self.backWhiteView removeFromSuperview];
            [self.backDeleteBtn removeFromSuperview];
            [self.backConfirmBtn removeFromSuperview];
            [self.backLabel removeFromSuperview];
            [self.backLineView removeFromSuperview];
            [self.backLabel1 removeFromSuperview];
            LoginNewViewController * login = [[LoginNewViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:login];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:@"ef4e42"];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            [self.navigationController presentViewController:navi animated:YES completion:nil];
}

#pragma mark 主页四个按钮
-(void)pressChildList{
    NSLog(@"学员名单");
    ChildListViewController * chivc = [[ChildListViewController alloc]init];
    [self.navigationController pushViewController:chivc animated:YES];
}
-(void)pressClassManage{
    NSLog(@"班级管理");
    ClassManageViewController * cmvc = [[ClassManageViewController alloc]init];
    [self.navigationController pushViewController:cmvc animated:YES];
}
-(void)pressTestPlan{
    NSLog(@"测试计划");
    TestPlanViewController * tvc =[[TestPlanViewController alloc]init];
    [self.navigationController pushViewController:tvc animated:YES];
}
-(void)pressSaleSituation{
    NSLog(@"营销场景");
    SaleSituationViewController * svc = [[SaleSituationViewController alloc]init];
    [self.navigationController pushViewController:svc animated:YES];
}

#pragma mark 同步数据
-(void)uploadData{
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //拿到本地数据
    NSMutableArray * localChildListArray = [_allDataDictionary objectForKey:@"ChildList"];
    NSMutableArray * localClassListArray = [_allDataDictionary objectForKey:@"ClassList"];
    NSMutableArray * localProgramsArray = [_allDataDictionary objectForKey:@"Programs"];
    NSMutableArray * localTestResultArray = [_allDataDictionary objectForKey:@"TestResult"];
    //遍历得到需要上传的数据
    //*****************************agencyid////////////////////////////////////////////////////////////////////
    NSInteger  agencyId = [[user objectForKey:@"AgencyId"]integerValue];
    //agencyid////////////////////////////////////////////////////////////////////
    
    //*****************************删除的对象////////////////////////////////////////////////////////////////////
    NSMutableDictionary * deletedDic = [[NSMutableDictionary alloc]init];
    //已经删除的孩子数组
    NSMutableArray * ChildIdArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteChildArray"] != nil) {
        
        NSString* str = [user objectForKey:@"deleteChildArray"];
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        ChildIdArr = [dict objectForKey:@"deleteChildArray"];
    }
    //已经删除的班级数组
    NSMutableArray * ClassArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteClassArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteClassArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        ClassArr = [dict1 objectForKey:@"deleteClassArray"];
    }
    //已经删除的测试计划数组
    NSMutableArray * PlanArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deletePlanArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deletePlanArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        PlanArr = [dict1 objectForKey:@"deletePlanArray"];
    }
    //已经删除的营销孩子数组
    NSMutableArray * MasterArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteMasterArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteMasterArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        MasterArr = [dict1 objectForKey:@"deleteMasterArray"];
    }
    
    //将这四个数组设置成对象
    [deletedDic setObject:PlanArr forKey:@"ProgramIdArr"];
    [deletedDic setObject:MasterArr forKey:@"MasterIdArr"];
    [deletedDic setObject:ChildIdArr forKey:@"ChildIdArr"];
    [deletedDic setObject:ClassArr forKey:@"ClassArr"];
    //删除的对象////////////////////////////////////////////////////////////////////
    
    //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadChildListArray = [[NSMutableArray alloc]init];//childlist
    for (NSMutableDictionary * dict in localChildListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadChildListArray addObject:dict];
        }
    }
    //待上传的孩子childlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadClassListArray = [[NSMutableArray alloc]init];//classlist
    for (NSMutableDictionary * dict in localClassListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadClassListArray addObject:dict];
        }
    }
    //待上传的班级classlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadProgramsArray = [[NSMutableArray alloc]init];//program
    for (NSMutableDictionary * dict in localProgramsArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadProgramsArray addObject:dict];
        }
    }
    //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadTestResultArray = [[NSMutableArray alloc]init];//masterDetail
    for (NSMutableDictionary * dict in localTestResultArray) {
        NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
        NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        int a = 0;
        //先判断MASTER
        NSInteger dictid =[[masterdic objectForKey:@"Id"]integerValue];
        if (dictid<0 || [masterdic objectForKey:@"1900V"] !=nil) {
            a+=1;
        }else{//master没有更新的话， 判断与之对应的detail
            for (NSMutableDictionary * detailDic in detailArr) {
                NSInteger dictid =[[detailDic objectForKey:@"Id"]integerValue];
                if (dictid<0 || [detailDic objectForKey:@"1900V"] !=nil) {
                    a+=1;
                }
            }
        }
        if (a!=0) {
            [newDICTIONARY setObject:masterdic forKey:@"ResultMaster"];
            [newDICTIONARY setObject:detailArr forKey:@"ResultDetail"];
            [readyToLoadTestResultArray addObject:newDICTIONARY];
        }
    }
    if (readyToLoadTestResultArray.count ==0) {
        //没有任何修改  给空数组和空字典
        NSMutableDictionary * dic1= [[NSMutableDictionary alloc]init];
        NSMutableArray * arr1 = [[NSMutableArray alloc]init];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        [newDICTIONARY setObject:dic1 forKey:@"ResultMaster"];
        [newDICTIONARY setObject:arr1 forKey:@"ResultDetail"];
        [readyToLoadTestResultArray addObject:newDICTIONARY];
    }
    //待上传的结果result////////////////////////////////////////////////////////////////////
    
    
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //开始上传
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        /////////////////////请求
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@",url);
        //        NSString * kuohao = @"[]";
        NSNumber * aId= [NSNumber numberWithInteger:agencyId];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
        //设置参数
        NSData * datachild = [NSJSONSerialization dataWithJSONObject:readyToLoadChildListArray options:0  error:nil];
        NSString * jsStrchild = [[NSString alloc]initWithData:datachild encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrchild1 = [self stringCutN:jsStr];
        
        NSData * dataclass = [NSJSONSerialization dataWithJSONObject:readyToLoadClassListArray options:0  error:nil];
        NSString * jsStrclass = [[NSString alloc]initWithData:dataclass encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrclass1 = [self stringCutN:jsStr];
        
        NSData * datapro = [NSJSONSerialization dataWithJSONObject:readyToLoadProgramsArray options:0  error:nil];
        NSString * jsStrpro = [[NSString alloc]initWithData:datapro encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrpro1 = [self stringCutN:jsStr];
        
        NSData * dataresult = [NSJSONSerialization dataWithJSONObject:readyToLoadTestResultArray options:0  error:nil];
        NSString * jsStrresult = [[NSString alloc]initWithData:dataresult encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //        NSString *  jsStrresult1 = [self stringCutN:jsStr];
        
        NSData *jsonDataPrama = [NSJSONSerialization dataWithJSONObject:deletedDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStringDic;
        jsonStringDic = [[NSString alloc]initWithData:jsonDataPrama encoding:NSUTF8StringEncoding];
        NSString *  useFulString1 = [self stringCutN:jsonStringDic];
        
        NSDictionary * parama = @{@"ServiceUnitId":aId,@"JsonChildList":jsStrchild,@"JsonClassList":jsStrclass,@"JsonProgramList":jsStrpro,@"JsonTestResult":jsStrresult,@"JsonDeleteObj":useFulString1};
        
        //            NSData * Pramadata = [NSJSONSerialization dataWithJSONObject:parama options:NSJSONWritingPrettyPrinted error:nil];
        //            NSString * pramaDic;
        //            pramaDic = [[NSString alloc]initWithData:Pramadata encoding:NSUTF8StringEncoding];
        //        NSString *  prama1 = [self stringCutN:pramaDic];
        ////
        //
        manager.requestSerializer.timeoutInterval = 30;
        [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"上传大数据 success");
            NSMutableDictionary *relationDict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary * newoldDic =[relationDict objectForKey:@"DeleteIdRelation"];//新旧关系
            
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            [user removeObjectForKey:@"deleteChildArray"];
            [user removeObjectForKey:@"deleteClassArray"];
            [user removeObjectForKey:@"deletePlanArray"];
            [user removeObjectForKey:@"deleteMasterArray"];
            /**********************************************************************************************************************************/
            //清除新数据的负数ID 和 1900V 改变字段
            //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
            NSMutableArray * childNewOld = [newoldDic objectForKey:@"ChildIdRelation"];
            for (NSMutableDictionary * dict in localChildListArray.reverseObjectEnumerator) {
                if ( [dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * childNewoldDic in childNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[childNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[childNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的孩子childlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
            NSMutableArray * classNewOld = [newoldDic objectForKey:@"ClassIdRelation"];
            for (NSMutableDictionary * dict in localClassListArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * classNewoldDic in classNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[classNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[classNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的班级classlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            NSMutableArray * programNewOld = [newoldDic objectForKey:@"ProgramIdRelation"];
            for (NSMutableDictionary * dict in localProgramsArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * programNewoldDic in programNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[programNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[programNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                    
                }
            }
            //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
            NSMutableArray * masterNewOld = [newoldDic objectForKey:@"MasterIdRelation"];
            for (NSMutableDictionary * dict in localTestResultArray.reverseObjectEnumerator) {
                NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
                NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
                //先判断MASTER
                if ([masterdic objectForKey:@"1900V"] !=nil) {
                    [masterdic removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * masterNewoldDic in masterNewOld) {
                    if ([[masterdic objectForKey:@"Id"]isEqual:[masterNewoldDic objectForKey:@"OldId"]] ) {
                        [masterdic removeObjectForKey:@"Id"];
                        [masterdic setObject:[masterNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
                //master没有更新的话， 判断与之对应的detail
                for (NSMutableDictionary * detailDic in detailArr) {
                    NSInteger dictid =[[detailDic objectForKey:@"Id"]integerValue];
                    if (dictid<0 || [detailDic objectForKey:@"1900V"] !=nil) {
                        [detailDic setObject:@1 forKey:@"Id"];
                        [detailDic removeObjectForKey:@"1900V"];
                    }
                }
                
            }
            //待上传的结果result////////////////////////////////////////////////////////////////////
            /**********************************************************************************************************************************/
            
            //将新孩子的负数ID替换? 营销场景
            if ([user objectForKey:@"finalSaleDic"]!=nil) {
                
                NSString * FS = [user objectForKey:@"finalSaleDic"];
                NSData * jsonData = [FS dataUsingEncoding:NSUTF8StringEncoding];
                NSMutableDictionary * mdic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray * masterIdArray = [mdic objectForKey:@"finalSaleDic"];
                NSMutableDictionary * newIDDic = [relationDict objectForKey:@"DeleteIdRelation"];//全部关系
                NSMutableArray * newIdArray = [newIDDic objectForKey:@"MasterIdRelation"];//MASTER关系
                
                //循环遍历 替换负数ID
                for ( NSNumber * oldId in masterIdArray.reverseObjectEnumerator) {
                    for (NSMutableDictionary * dic in newIdArray) {
                        if ([oldId isEqual:[dic objectForKey:@"OldId"]]) {
                            [masterIdArray removeObject:oldId];
                            [masterIdArray addObject:[dic objectForKey:@"NewId"]];
                        }
                    }
                }
                
                [mdic removeObjectForKey:@"finalSaleDic"];
                [mdic setObject:masterIdArray forKey:@"finalSaleDic"];
                
                NSData * dataDic = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:nil];
                NSString * FSS = [[NSString alloc]initWithData:dataDic encoding:NSUTF8StringEncoding];
                //
                
                [user removeObjectForKey:@"finalSaleDic"];
                [user setObject:FSS forKey:@"finalSaleDic"];
                
                [user synchronize];
            }
            [self reloadAllData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传大数据 error");
            NSError * err = error;
            [self showMessage:@"同步失败，请稍后重试"];
            NSLog(@"登陆因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
    }
    
}

#pragma mark
#pragma mark 同步数据
-(void)reloadAllData{
    NSLog(@"开始同步");
    //检测网络
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * kuohao =@"[]";
        NSDictionary *parama = @{@"ServiceUnitId":[user objectForKey:@"AgencyId"],@"ChildList":kuohao,@"ClassList":kuohao,@"ProgramList":kuohao};
        [[HttpRequest sharedInstance] postWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"更新成功");
            
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            //将未分班放在最后
            NSMutableArray * classArray=[NSMutableArray array];
            classArray = [dict objectForKey:@"ClassList"];
            NSDictionary * unClassed = [[NSDictionary alloc]init];
            for (NSDictionary*dic in classArray.reverseObjectEnumerator) {
                if ([[dic objectForKey:@"Name"]isEqualToString:@"未分班"]) {
                    unClassed = dic;
                    [classArray removeObject:dic];
                    
                }
            }
            //        [classArray insertObject:unClassed atIndex:0];
            [classArray addObject:unClassed];
            [dict removeObjectForKey:@"ClassList"];
            [dict setObject:classArray forKey:@"ClassList"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString * allstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            //
            [user removeObjectForKey:@"AllData"];
            [user setObject:allstr forKey:@"AllData"];
            [user synchronize];
            [self.mainView.myTableView removeFromSuperview];
            [self.mainLeftView removeFromSuperview];
            [self getData];
            [self showMessage:@"同步成功"];
            
        } failure:^(NSError *error) {
            [self showMessage:@"同步失败，请稍后再试"];
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
        
    }
}


#pragma mark 上传问题数据
-(void)uploadProblemData{
    [UIView animateWithDuration:0.5 animations:^{
        _mainLeftView.frame = CGRectMake(-380*AutoScaleHorizontal, 0, 350*AutoScaleHorizontal, SCREEN_HEIGHT);
    }];
    [_backView removeFromSuperview];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //拿到本地数据
    NSMutableArray * localChildListArray = [_allDataDictionary objectForKey:@"ChildList"];
    NSMutableArray * localClassListArray = [_allDataDictionary objectForKey:@"ClassList"];
    NSMutableArray * localProgramsArray = [_allDataDictionary objectForKey:@"Programs"];
    NSMutableArray * localTestResultArray = [_allDataDictionary objectForKey:@"TestResult"];
    //遍历得到需要上传的数据
    //*****************************agencyid////////////////////////////////////////////////////////////////////
    NSInteger  agencyId = [[user objectForKey:@"AgencyId"]integerValue];
    //agencyid////////////////////////////////////////////////////////////////////
    
    //*****************************删除的对象////////////////////////////////////////////////////////////////////
    NSMutableDictionary * deletedDic = [[NSMutableDictionary alloc]init];
    //已经删除的孩子数组
    NSMutableArray * ChildIdArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteChildArray"] != nil) {
        
        NSString* str = [user objectForKey:@"deleteChildArray"];
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        ChildIdArr = [dict objectForKey:@"deleteChildArray"];
    }
    //已经删除的班级数组
    NSMutableArray * ClassArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteClassArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteClassArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        ClassArr = [dict1 objectForKey:@"deleteClassArray"];
    }
    //已经删除的测试计划数组
    NSMutableArray * PlanArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deletePlanArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deletePlanArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        PlanArr = [dict1 objectForKey:@"deletePlanArray"];
    }
    //已经删除的营销孩子数组
    NSMutableArray * MasterArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteMasterArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteMasterArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        MasterArr = [dict1 objectForKey:@"deleteMasterArray"];
    }
    
    //将这四个数组设置成对象
    [deletedDic setObject:PlanArr forKey:@"ProgramIdArr"];
    [deletedDic setObject:MasterArr forKey:@"MasterIdArr"];
    [deletedDic setObject:ChildIdArr forKey:@"ChildIdArr"];
    [deletedDic setObject:ClassArr forKey:@"ClassArr"];
    //删除的对象////////////////////////////////////////////////////////////////////
    
    //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadChildListArray = [[NSMutableArray alloc]init];//childlist
    for (NSMutableDictionary * dict in localChildListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadChildListArray addObject:dict];
        }
    }
    //待上传的孩子childlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadClassListArray = [[NSMutableArray alloc]init];//classlist
    for (NSMutableDictionary * dict in localClassListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadClassListArray addObject:dict];
        }
    }
    //待上传的班级classlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadProgramsArray = [[NSMutableArray alloc]init];//program
    for (NSMutableDictionary * dict in localProgramsArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadProgramsArray addObject:dict];
        }
    }
    //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadTestResultArray = [[NSMutableArray alloc]init];//masterDetail
    for (NSMutableDictionary * dict in localTestResultArray) {
        NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
        NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        int a = 0;
        //先判断MASTER
        NSInteger dictid =[[masterdic objectForKey:@"Id"]integerValue];
        if (dictid<0 || [masterdic objectForKey:@"1900V"] !=nil) {
            a+=1;
        }else{//master没有更新的话， 判断与之对应的detail
            for (NSMutableDictionary * detailDic in detailArr) {
                NSInteger dictid =[[detailDic objectForKey:@"Id"]integerValue];
                if (dictid<0 || [detailDic objectForKey:@"1900V"] !=nil) {
                    a+=1;
                }
            }
        }
        if (a!=0) {
            [newDICTIONARY setObject:masterdic forKey:@"ResultMaster"];
            [newDICTIONARY setObject:detailArr forKey:@"ResultDetail"];
            [readyToLoadTestResultArray addObject:newDICTIONARY];
        }
    }
    if (readyToLoadTestResultArray.count ==0) {
        //没有任何修改  给空数组和空字典
        NSMutableDictionary * dic1= [[NSMutableDictionary alloc]init];
        NSMutableArray * arr1 = [[NSMutableArray alloc]init];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        [newDICTIONARY setObject:dic1 forKey:@"ResultMaster"];
        [newDICTIONARY setObject:arr1 forKey:@"ResultDetail"];
        [readyToLoadTestResultArray addObject:newDICTIONARY];
    }
    //待上传的结果result////////////////////////////////////////////////////////////////////
    
    
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //开始上传
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        /////////////////////请求
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/physicalTest2/uploadRawText";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@",url);
        NSNumber * aId= [NSNumber numberWithInteger:agencyId];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
        //设置参数
        NSData * datachild = [NSJSONSerialization dataWithJSONObject:readyToLoadChildListArray options:0  error:nil];
        NSString * jsStrchild = [[NSString alloc]initWithData:datachild encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrchild1 = [self stringCutN:jsStr];
        
        NSData * dataclass = [NSJSONSerialization dataWithJSONObject:readyToLoadClassListArray options:0  error:nil];
        NSString * jsStrclass = [[NSString alloc]initWithData:dataclass encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrclass1 = [self stringCutN:jsStr];
        
        NSData * datapro = [NSJSONSerialization dataWithJSONObject:readyToLoadProgramsArray options:0  error:nil];
        NSString * jsStrpro = [[NSString alloc]initWithData:datapro encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrpro1 = [self stringCutN:jsStr];
        
        NSData * dataresult = [NSJSONSerialization dataWithJSONObject:readyToLoadTestResultArray options:0  error:nil];
        NSString * jsStrresult = [[NSString alloc]initWithData:dataresult encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //        NSString *  jsStrresult1 = [self stringCutN:jsStr];
        
        NSData *jsonDataPrama = [NSJSONSerialization dataWithJSONObject:deletedDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStringDic;
        jsonStringDic = [[NSString alloc]initWithData:jsonDataPrama encoding:NSUTF8StringEncoding];
        NSString *  useFulString1 = [self stringCutN:jsonStringDic];
        ////////////////
        
        NSDictionary * parama = @{@"ServiceUnitId":aId,@"JsonChildList":jsStrchild,@"JsonClassList":jsStrclass,@"JsonProgramList":jsStrpro,@"JsonTestResult":jsStrresult,@"JsonDeleteObj":useFulString1};
        
        
        /////////将问题数据合并成字典，将此字典作为参数传递。
        
        NSData * Pramadata = [NSJSONSerialization dataWithJSONObject:parama options:NSJSONWritingPrettyPrinted error:nil];
        NSString * pramaDic;
        pramaDic = [[NSString alloc]initWithData:Pramadata encoding:NSUTF8StringEncoding];
        NSString *  prama1 = [self stringCutN:pramaDic];
        
        NSDictionary * parama12 = @{@"ServiceUnitId":aId,@"RawText":prama1};
        //
        //
        manager.requestSerializer.timeoutInterval = 30;
        [manager POST:url parameters:parama12 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"上传问题数据 success");
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            [self showMessage:@"问题反馈成功"];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传问题数据 error");
            NSError * err = error;
            [self showMessage:@"同步失败，请稍后重试"];
            NSLog(@"失败%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传失败，请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alc addAction:act];
            [self presentViewController:alc animated:YES completion:nil];
        }];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
